package com.marktotop.exception;

import com.marktotop.response.ResultBean;
import com.marktotop.response.ResultCode;
import org.springframework.core.NestedRuntimeException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * GlobalException 全局异常处理
 *
 * @author WXLD
 * @Data 2021/6/21
 * @Since 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * SQLException 异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public ResultBean mysqlExceptionHandler(SQLException e){
        if (e instanceof SQLIntegrityConstraintViolationException){
            return ResultBean.result(ResultCode.HAS_FOREIGN_KEY);
        }
        return ResultBean.result(ResultCode.DATABASE_ERROR);
  }


    @ExceptionHandler(NestedRuntimeException.class)
    public ResultBean systemIOExceptionHandler(NestedRuntimeException e){
        if (e instanceof DataAccessResourceFailureException){
            return ResultBean.result(ResultCode.REDIS_CONNECTION_ERROR);
        }
        return ResultBean.result(ResultCode.IO_ERROR);
    }
}
